﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SceneCreator2 : BaseGame {


	public GameObject staffLeft = null;
	public GameObject staffRight = null;

	public GameObject staffsLeft = null;
	public GameObject staffsRight = null;

    public GameObject orange = null;
    public GameObject watermelon = null;
    public GameObject papaya = null;

	public float originY = -340;

	private static SceneCreator2 instance = null;
	public static SceneCreator2 GetInstance()
	{
		return instance;
	}

	void Awake()
	{
		instance = this;
	}

	void Start()
	{
//		originY = staffsLeft.transform.localPosition.y;
	}
		

    public void TurnFruit( GameObject go, bool toBroke = true )
    {
        Transform normal = go.transform.GetChild(0);
        Transform broke = go.transform.GetChild(1);

        normal.gameObject.SetActive(!toBroke);
        broke.gameObject.SetActive(toBroke);
    }


	public override void Init( string id, string lessonID = "")
	{
		gameCfg = DataManager.gameCfgData.GetCfg (id);
		if (gameCfg == null)
			return;
        lessonId = lessonID;
        hasBegin = false;

        music.clip = null;
        nowGame = this;
        // 关闭游戏1
        SceneCreator.GetInstance().CloseGame();
		// 暂时关闭游戏2
		gameObject.SetActive(false);

		isVideoFinished = false;
        //		PlayVideoFirst (gameCfg.urlVideo);

        if (gameUI.GetInstance() != null)
            gameUI.GetInstance().RefreshScore(0, 0);

        gameVideoUI.StartVideo(gameCfg.urlVideo);

		ReInit ();
	}



	bool preparedReady = false;
	public override void ReInit( bool mansu = true)
	{
		if (gameCfg == null)
			return;


		nowGame = this;

		Clear ();

		hasBegin = false;
		preparedReady = false;

		isBusyLeft = false;
		isBusyRight = false;

		gameUI.GetInstance ().HideReward ();
		basketCollierCheck.CloseGuide ();

		staffsLeft.transform.localPosition = new Vector3 (staffsLeft.transform.localPosition.x, originY, 0);
		staffsRight.transform.localPosition = new Vector3 (staffsRight.transform.localPosition.x, originY, 0);


		score = 0;

		bool firstLeft = true;
		bool firstRight = true;


        if (lessonId != "1" && lessonId != "2")
        {
            firstRight = false;
            firstLeft = false;
        }


        GameObject lastone = null;
		GameObject firstone = null;

        nowMansu = mansu;
        float offsetY = mansu ? -120f : 0;

        cf = mansu ? gameCfg.mansu : gameCfg.kuaisu;
		// 直接创造所有水果
		foreach (var item in cf.gudian) {

            GameObject templet = null;
            switch( item.Value )
            {
                case "1":
                    {
                        templet = orange;
                    }
                    break;
                case "2":
                    {
                        templet = papaya;
                    }
                    break;
                case "3":
                    {
                        templet = watermelon;
                    }
                    break;
            }

            if (templet == null)
                continue;
		
			GameObject go = Instantiate (templet) as GameObject;
			go.SetActive (true);
			go.name = "staffLeft";
			go.transform.parent = staffLeft.transform.parent;
			go.transform.localScale = staffLeft.transform.localScale;
			go.transform.localRotation = staffLeft.transform.localRotation;
			go.transform.localPosition = staffLeft.transform.localPosition + new Vector3 (0,item.Key * cf.speed*100 + offsetY, 0);

            TurnFruit(go, false);

            if (firstLeft) {
				firstone = go;
				firstLeft = false;
			}

			lastone = go;
		}

		foreach (var item in cf.gudian2) {

            GameObject templet = null;
            switch (item.Value)
            {
                case "1":
                    {
                        templet = orange;
                    }
                    break;
                case "2":
                    {
                        templet = papaya;
                    }
                    break;
                case "3":
                    {
                        templet = watermelon;
                    }
                    break;
            }

            if (templet == null)
                continue;

            GameObject go = Instantiate (templet) as GameObject;
			go.SetActive (true);
			go.name = "staffRight";
			go.transform.parent = staffRight.transform.parent;
			go.transform.localScale = staffRight.transform.localScale;
			go.transform.localRotation = staffRight.transform.localRotation;
			go.transform.localPosition = staffRight.transform.localPosition + new Vector3 (0,item.Key * cf.speed*100 + offsetY, 0);

            TurnFruit(go, false);

			if (firstRight) {
				
				firstRight = false;

				if (go.transform.localPosition.y < firstone.transform.localPosition.y) {
					go.tag = "firstRight";
				}
				else
					firstone.tag = "firstLeft";
			}

			if ( go.transform.localPosition.y > lastone.transform.localPosition.y)
				lastone = go;
		}

		lastone.tag = "lastGudian";


//        if (music.clip == null)
        //		if (music.clip != null)
        //			Invoke("DelayPrepareReady", 1f);
        //			BeginGame ();
        //		else 
        {
		
			if (!string.IsNullOrEmpty (cf.urlMusic)) {
				Loading.GetInstance ().StartLoading ();
				ResLoader.Load(cf.urlMusic, null, (www)=>{
					AudioClip ac = null;
					if (string.IsNullOrEmpty( www.error ) )
						ac = WWWAudioExtensions.GetAudioClip (www);

					music.clip = ac;
					Loading.GetInstance().EndLoading();

//					preparedReady = true;
					Invoke("DelayPrepareReady", 1f);
				}, true, true);
			}
		}
//        else
//            Invoke("DelayPrepareReady", 1f);
    }

	public void DelayPrepareReady()
	{
		preparedReady = true;
	}

    public override void OnBtnStartGame()
    {
        preparedReady = true;
    }

    void FixedUpdate()
	{
		if (preparedReady && isVideoFinished)
			BeginGame ();

//		Debug.Log ("hasbegin = " + hasBegin.ToString());
		if (!hasBegin)
			return;

		float deltaDistance = Time.fixedDeltaTime* cf.speed * 100;
		staffsLeft.transform.position= staffsLeft.transform.position - new Vector3 (0, deltaDistance, 0);
		staffsRight.transform.position= staffsRight.transform.position - new Vector3 (0, deltaDistance, 0);

//		Debug.Log (staffsRight.transform.position + "        time:" + music.time);
	}


	public override void BeginGame()
	{
		preparedReady = false;

		if(gameUI.GetInstance() != null )
			gameUI.GetInstance ().RefreshScore (0, cf.gudian.Count+cf.gudian2.Count, true);

		music.Stop ();
		Debug.Log ("music play");
		music.Play ();

		

		hasBegin = true;
	}



	public GameObject basketLeft = null;
	public GameObject basketRight = null;

	bool isBusyLeft = false;
	public void OnBtnLeft()
	{
		// close guide
		basketCollierCheck.CloseGuide();
		BaseGame.nowGame.UnPause ();

		if (isBusyLeft)
			return;

		isBusyLeft = true;
		LeanTween.scale (basketLeft, new Vector3 (1.2f, 1.2f, 1.2f), 0.05f).setLoopPingPong (1).setOnComplete(
			()=>{
				isBusyLeft =false;
			}
		).tweenType = LeanTweenType.easeOutExpo;



		if (basketCollierCheck.nowStaffLeft != null ) {
            // operate
            //			LeanTween.moveY(basketCollierCheck.nowStaffLeft, cf.speed * 100f , 0.3f).setDestroyOnComplete(true).tweenType = LeanTweenType.easeOutExpo;
            //			LeanTween.alphaCanvas (basketCollierCheck.nowStaffLeft.GetComponent<CanvasGroup> (), 0.1f, 0.3f);

            TurnFruit(basketCollierCheck.nowStaffLeft);

			basketCollierCheck.nowStaffLeft = null;




			// add score
			AddScore(true);
		}
		
	}


	bool isBusyRight = false;
	public void OnBtnRight()
	{
		// close guide
		basketCollierCheck.CloseGuide();
		BaseGame.nowGame.UnPause ();

		if (isBusyRight)
			return;

		isBusyRight = true;
		LeanTween.scale (basketRight, new Vector3 (1.2f, 1.2f, 1.2f), 0.05f).setLoopPingPong (1).setOnComplete(
			()=>{
				isBusyRight =false;
			}
		).tweenType = LeanTweenType.easeOutExpo;

		if (basketCollierCheck.nowStaffRight != null ) {
			// operate
//			LeanTween.moveY(basketCollierCheck.nowStaffRight, cf.speed * 100, 0.3f).setDestroyOnComplete(true).tweenType = LeanTweenType.easeOutExpo;
//			LeanTween.alphaCanvas (basketCollierCheck.nowStaffRight.GetComponent<CanvasGroup> (), 0.1f, 0.3f);
            TurnFruit(basketCollierCheck.nowStaffRight);

            basketCollierCheck.nowStaffRight = null;



			// add score
			AddScore(true);
		}
	}


	public override void Clear()
	{
		// 销毁之前的
		for (int i = staffLeft.transform.parent.childCount -1; i >0; i--) {
		
			GameObject o = staffLeft.transform.parent.GetChild (i).gameObject;
			GameObject.Destroy (o);
		}

		// 销毁之前的
		for (int i = staffRight.transform.parent.childCount -1; i >0; i--) {

			GameObject o = staffRight.transform.parent.GetChild (i).gameObject;
			GameObject.Destroy (o);
		}

		Resources.UnloadUnusedAssets ();
	}


	public override void CloseGame()
	{
		Clear ();

		music.clip = null;

		gameObject.SetActive (false);
	}

	

	public override void Replay()
	{
		Time.timeScale = 1;

		ReInit (nowMansu);
	}



}
